import { Component, ViewChild, Injector, Output, EventEmitter, ViewEncapsulation, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import {
  PromotionServiceProxy,
  PromotionInputDto,
  AjaxResponseOfListOfNullableOfInt32,
  ListResultDtoOfCategoryOutputDto,
  CategoryOutputDto,
  ListResultDtoOfCityOutDto,
  CityServiceProxy,
  CityOutDto
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/app-component-base';
import { AppConsts } from '@shared/AppConsts';
import { WebUploaderComponent, File, FileStatus, Options, OptionsAccept } from 'ngx-webuploader';
import { varToEnumStringVal } from '@shared/helpers/UrlHelper';

@Component({
  selector: 'app-promotion-add',
  templateUrl: './promotion-add.component.html',
  styleUrls: ['./promotion-add.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class PromotionAddComponent extends AppComponentBase {
  @ViewChild('createPromotionModal') modal: ModalDirective;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active: boolean = false;
  saving: boolean = false;
  graphicContent: string = '';

  categories: CategoryOutputDto[];
  nullObj: CityOutDto = new CityOutDto();
  promotion: PromotionInputDto = null;
  provinces: ListResultDtoOfCityOutDto = new ListResultDtoOfCityOutDto();
  cities: ListResultDtoOfCityOutDto = new ListResultDtoOfCityOutDto();
  districts: ListResultDtoOfCityOutDto = new ListResultDtoOfCityOutDto();
  imgOptions: Options = {
    server: AppConsts.remoteServiceBaseUrl + '/file/upload',
    // 自动上传。
    auto: true,
    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: '#filePicker',
    formData: { 'associateType': 'PromotionHeader', 'objectId': '' },
    // 只允许选择文件，可选。
    accept: <OptionsAccept>{
      title: 'Media'
    }
  };
  editorConfig: any = {
    configUrl: AppConsts.appBaseUrl + '/assets/ueditor/config.json',
    imageUploadUrl: AppConsts.remoteServiceBaseUrl + '/file/upload',
    imageUploadFormData: { 'associateType': 'PromotionContent', 'objectId': '' },
    imageUrlPrefix: AppConsts.remoteServiceBaseUrl + '/file/download/',
    imageManagerUrl: AppConsts.remoteServiceBaseUrl + '/file/getwithtype/PromotionContent',
    imageManagerUrlPrefix: AppConsts.remoteServiceBaseUrl + '/file/download/',
    initialFrameHeight: 400,
    toolbars: [
      [
        'source', '|', 'undo', 'redo', '|',
        'bold', 'italic', 'underline', 'fontborder', 'strikethrough',
        'superscript', 'subscript', 'removeformat', 'formatmatch',
        'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
        'backcolor', 'insertorderedlist', 'insertunorderedlist',
        'selectall', 'cleardoc', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
        'customstyle', 'fontsize', '|',
        'directionalityltr', 'directionalityrtl', 'indent', '|',
        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
        'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
        'insertimage', 'horizontal', 'spechars',
        'preview'
      ]
    ]
  };
  constructor(
    injector: Injector,
    private _promotionService: PromotionServiceProxy,
    private _cityService: CityServiceProxy
  ) {
    super(injector);
    this.nullObj.id = undefined;
    this.nullObj.name = '--请选择--';
    this.provinces.items = [this.nullObj];
    this.cities.items = [this.nullObj];
    this.districts.items = [this.nullObj];
  }

  show( id?: number): void {
    this.active = true;
    this.getCities();
    if (id) {
      this.getEditorDto(id);
    } else {
      this.promotion = new PromotionInputDto();
      this.promotion.showForUserTypes = ["FirstAgentUser"];
      this.promotion.attachmentIds = [];
      this.modal.show();
    }
  }
  getEditorDto(id: number): void {
    this._promotionService.getPromotionInputDtoForEditAsync(id).subscribe((result: PromotionInputDto) => {
      this.promotion = result;
      this.modal.show();
    });
  }

  save(): void {
    this.saving = true;
    this._promotionService.savePromotionAsync(this.promotion)
      .finally(() => { this.saving = false; })
      .subscribe(() => {
        this.notify.info('保存成功!');
        this.close();
        this.modalSave.emit(null);
      });
  }

  changeTargetUserType(userType:string):void{
    if(this.promotion.showForUserTypes.indexOf(userType)>=0){
      this.promotion.showForUserTypes = this.promotion.showForUserTypes.splice(this.promotion.showForUserTypes.indexOf(userType),1);
    }else{
      this.promotion.showForUserTypes.push(userType);
    }
  }


  onImgReady(uploader: WebUploaderComponent) {
    let $list = $('#fileList');
    // 优化retina, 在retina下这个值是2
    let ratio = window.devicePixelRatio || 1;
    // 缩略图大小
    let thumbnailWidth = 100 * ratio;
    let thumbnailHeight = 100 * ratio;
    var self = this;
    // 当有文件添加进来的时候
    uploader.Instance.on('fileQueued', function (file) {
      var $li = $(
        '<div id="' + file.id + '" class="file-item thumbnail">' +
        '<img>' +
        '<div class="info">' + file.name + '</div>' +
        '</div>'
      ),
        $img = $li.find('img');

      //$list.append($li);

      // 创建缩略图
      uploader.Instance.makeThumb(file, function (error, src) {
        if (error) {
          $img.replaceWith('<span>不能预览</span>');
          return;
        }

        $img.attr('src', src);
      }, thumbnailWidth, thumbnailHeight);
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.Instance.on('uploadProgress', function (file, percentage) {
      let $li = $('#' + file.id),
        $percent = $li.find('.progress span');

      // 避免重复创建
      if (!$percent.length) {
        $percent = $('<p class="progress"><span></span></p>')
          .appendTo($li)
          .find('span');
      }

      $percent.css('width', percentage * 100 + '%');
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.Instance.on('uploadSuccess', function (file, result) {
      const obj = new AjaxResponseOfListOfNullableOfInt32();
      obj.init(result);
      obj.result.forEach(element => {
        self.promotion.attachmentIds.push(element);
      });

      $('#' + file.id).addClass('upload-state-done');
    });

    // 文件上传失败，现实上传出错。
    uploader.Instance.on('uploadError', function (file) {
      let $li = $('#' + file.id),
        $error = $li.find('div.error');

      // 避免重复创建
      if (!$error.length) {
        $error = $('<div class="error"></div>').appendTo($li);
      }

      $error.text('上传失败');
    });

    // 完成上传完了，成功或者失败，先删除进度条。
    uploader.Instance.on('uploadComplete', function (file) {
      $('#' + file.id).find('.progress').remove();
    });
  }

  onImgDestroy() {
    console.log('onDestroy');
  }

  onEditorReady(): void {
    console.log('onEditorReady', arguments);
  }
  onEditorDestroy(): void {
    console.log('onEditorDestroy', arguments);
  }
  onEditorContentChange(): void {
    console.log('onEditorContentChange', arguments);
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }

  getCities(id?: number): void {
    this._cityService.getByParentId(id)
      .subscribe((result: ListResultDtoOfCityOutDto) => {
        if (!id) {
          this.provinces = result;
          this.provinces.items.unshift(this.nullObj);
        } else {
          if (id.toString().length === 2) {
            this.cities = result;
            this.cities.items.unshift(this.nullObj);
          } else {
            this.districts = result;
            this.districts.items.unshift(this.nullObj);
          }
        }
      });
  }
  provinceChange(id: any): void {
    this.promotion.provinceId = id;
    this.promotion.cityId = undefined;
    this.promotion.districtId = undefined;
    this.districts.items = [this.nullObj];
    this.getCities(this.promotion.provinceId);
  }
  cityChange(id: any): void {
    this.promotion.cityId = id;
    this.promotion.districtId = undefined;
    this.getCities(this.promotion.cityId);
  }
}
